﻿using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using Actya.Core.Infrastructure.Logging;
using Actya.Core.Infrastructure.Mef;
using Autofac;
using Autofac.Core;

namespace Actya.Web.Infrastructure.Autofac
{
	public class PluginModule : Module
	{
		private readonly CompositionContainer _mefContainer;
		private readonly ILogger _logger = LogManager.GetLogger(typeof(PluginModule));

		public PluginModule(string pluginsDirectory)
		{
			var shadowCopyDirectory = PluginManager.ShadowCopyDirectory;
			var pluginAssemblies = Directory.EnumerateFiles(pluginsDirectory, "*.dll", SearchOption.AllDirectories).ToArray();

			// Don't use MEF at all when there are no plugins. This way we might be able to run under Medium Trust.
			if (pluginAssemblies.Any())
			{
				var pluginCatalog = new PluginDirectoryCatalog(shadowCopyDirectory);
				this._mefContainer = new CompositionContainer(pluginCatalog);
			}
		}

		protected override void Load(ContainerBuilder builder)
		{
			// Add plugin modules
			if (this._mefContainer != null)
			{
				foreach (var module in this._mefContainer.GetExportedValues<IModule>())
				{
					builder.RegisterModule(module);
				}
			}
		}
	}
}